<template>
    <a-modal v-if="state.open" v-model:open="state.open" :title="props.mode === 'single' ? '选择用户(单选)' : '选择用户(多选)'" width="820px" @ok="handleOk" @cancel="handleClose">
        <div class="select-org-user">
            <!-- 面包屑导航 -->
            <div class="org-breadcrumb-scroll" v-if="state.breadcrumb.length>0">
                <a-breadcrumb class="org-breadcrumb">
                    <a-breadcrumb-item v-for="(dept, idx) in state.breadcrumb" :key="dept.id"
                        @click="handleBreadcrumbClick(dept)" :class="{ clickable: idx !== state.breadcrumb.length - 1 }">
                        {{ dept.name }}
                    </a-breadcrumb-item>
                </a-breadcrumb>
            </div>
            <div class="org-user-content">
                <!-- 部门树 -->
                <div class="org-tree card">
                    <div class="tree-title">部门结构</div>
                    <a-tree :tree-data="state.curDeptUsers"
                        :field-names="{ title: 'name', key: 'id', children: 'children' }" :defaultExpandAll="true"
                        @select="handleDeptSelect" />
                </div>
                <!-- 用户列表 -->
                <div class="user-list card">
                    <div class="user-list-title">用户列表</div>
                    <a-list :data-source="state.userList" :split="false">
                        <template #renderItem="{ item }">
                            <a-list-item class="user-list-item" @mouseenter="hoverUser = item.id"
                                @mouseleave="hoverUser = null">
                                <a-checkbox v-model:checked="item.checked" :disabled="item.disabled" @change="toggleUser(item)">
                                    <span :class="{ 'user-hover': hoverUser === item.id }">{{ item.realName }}</span>
                                </a-checkbox>
                            </a-list-item>
                        </template>
                        <template #empty>
                            <div class="empty-tip">暂无成员</div>
                        </template>
                    </a-list>
                </div>
            </div>
            <!-- 已选用户 -->
            <div class="selected-users card">
                <div class="selected-title">已选成员：</div>
                <div class="selected-tags">
                    <a-tag v-for="user in state.selectedUsers" :key="user.id" closable color="green"
                        @close="() => removeUser(user)">
                        {{ user.realName }}
                    </a-tag>
                    <span v-if="!state.selectedUsers.length" class="empty-tip">未选择成员</span>
                </div>
            </div>
        </div>
    </a-modal>
</template>

<script setup lang="ts">
import { apiSysOrgGetDeptUsers } from '@/api/sys/sysOrg';
import type { ResType } from '@/api/types';
import { cloneDeep } from 'lodash';
import { reactive, ref } from 'vue';

const props = withDefaults(defineProps<{
    mode?:string
}>(),{
    mode:"single" //multiple
})

const emits = defineEmits<{
    (e: 'save', val: any): void
}>()

const state = reactive<any>({
    open: false,
    currentDept: null,
    breadcrumb: [],
    userList: [],
    selectedUsers: [],
    originDeptUser: [],
    curDeptUsers: []
});

const hoverUser = ref<string | null>(null);

const handleOk = () => {
    // 返回已选用户
    state.open = false;
    emits('save', state.selectedUsers)
    handleClose()
};

const handleQuery = async () => {
    const res = await apiSysOrgGetDeptUsers() as ResType<any[]>
    state.originDeptUser = res.data.result
    state.curDeptUsers = state.originDeptUser
}

const handleOpen = async (directorId?:any) => {
    state.open = true;
    await handleQuery()
    if(directorId){
        initWithUserId(directorId)
    }
};

// 传入负责人id，根据负责人id设置已选用户
const initWithUserId = (userID:any | any[])=>{
    // 当前已选部门可以不设置，只设置用户列表状态和已选用户
    function mapData (data:any[]){
        for (const dept of data) {
            const users = Array.isArray(dept.users) ? dept.users : [];
            for (const user of users) {
                if(props.mode == 'single') {
                    userID = Array.isArray(userID) ? userID[0] : userID
                    if(user.id == userID){
                        user.checked = true
                        user.disabled = false
                        state.selectedUsers = [user]
                        handleSetUserStatus()
                    }
                }else{
                    if(userID.includes(user.id)){
                        user.checked = true
                        state.selectedUsers.push(user)
                    }
                }
            }
            if(Array.isArray(dept.children)){
                mapData(dept.children)
            }
        }
    }
    mapData(state.curDeptUsers)
}

const handleClose = () => {
    state.open = false;
    state.currentDept = []
    state.breadcrumb = []
    state.userList = []
    state.selectedUsers = []
};

const handleDeptSelect = (selectedKeys: any, info: any) => {
    state.currentDept = info.node; //当前点击部门
    state.userList = Array.isArray(state.currentDept.users) ? state.currentDept.users : [];
    setBreadCrumb()
};

const setBreadCrumb = () => {
    state.breadcrumb = []
    function findAncestors(data: any[], targetId: any) {
        const res: any[] = []
        function traverse(data: any[], targetId: any) {
            for (const i of data) {
                if (i.id == targetId) {
                    res.push(i)
                    return true
                } else if (Array.isArray(i.children)) {
                    if (traverse(i.children, targetId)) {
                        res.push(i)
                        return true
                    }
                }
            }
            return false
        }
        traverse(data, targetId)
        return res
    }
    let breadcrumbArr = findAncestors(cloneDeep(state.curDeptUsers), state.currentDept.id)
    breadcrumbArr = breadcrumbArr.reverse()
    state.breadcrumb = breadcrumbArr
}

const handleBreadcrumbClick = (dept:any) => {
    state.currentDept = dept
    state.userList = Array.isArray(state.currentDept.users) ? state.currentDept.users : [];
    setBreadCrumb()
};


const toggleUser = (user: any) => {
    if (props.mode === 'single') {
        user.checked ? state.selectedUsers = [user] : state.selectedUsers = []
        handleSetUserStatus()
    }else{
        const id = state.selectedUsers.findIndex((u: any) => u.id === user.id);
        if (id !== -1) {
            state.selectedUsers.splice(id, 1);
        }else {
            state.selectedUsers.push(user)
        }
    }
};

// 设置用户列表禁用和启用
const handleSetUserStatus = ()=>{
    if (props.mode === 'single'){
        function toggleUserStatus(data:any[]) {
            for (const item of data) {
                if(Array.isArray(item.users)){
                    item.users.forEach((user: any) => {
                        // 若无选中情况，则不禁用
                        if(state.selectedUsers.length == 0) {
                            user.disabled = false
                            return
                        }
                        user.checked == true ? user.disabled = false : user.disabled = true
                    })
                }
                if(Array.isArray(item.children)){
                    toggleUserStatus(item.children)
                }
            }
        }
        toggleUserStatus(state.curDeptUsers)
    }
}

const removeUser = (user: any) => {
    user.checked = false
    toggleUser(user)
};

defineExpose({
    handleOpen
});
</script>

<style lang='scss' scoped>
.select-org-user {
    user-select: none;
    background: #f6f8fa;
    padding: 15px 4px 4px 4px;
    border-radius: 8px;

    // 面包屑横向滚动
    .org-breadcrumb-scroll {
        width: 100%;
        max-width: 100%;
        overflow-x: auto;

        .org-breadcrumb {
            display: inline-flex;
            min-width: max-content;
            background: #e6f7ff;
            padding: 8px 16px;
            border-radius: 6px;
            font-size: 15px;
            margin-bottom: 18px;

            .clickable {
                color: #1890ff;
                cursor: pointer;

                &:hover {
                    text-decoration: underline;
                }
            }
        }
    }

    .org-breadcrumb-scroll::-webkit-scrollbar {
        height: 8px;
        background: #f0f0f0;
    }

    .org-breadcrumb-scroll::-webkit-scrollbar-thumb {
        background: #b2eaff;
        border-radius: 4px;
    }

    .org-user-content {
        display: flex;
        gap: 24px;
        margin-bottom: 18px;
        .card {
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 8px #e6f7ff55;
            padding: 18px 16px 12px 16px;
            min-height: 320px;
        }

        .org-tree {
            width: 220px;
            border-right: 1px solid #f0f0f0;
            max-height: 240px;
            overflow-y: auto;

            &::-webkit-scrollbar {
                width: 6px;
                background: transparent;
            }

            &::-webkit-scrollbar-thumb {
                background: #e6f7ff;
                border-radius: 3px;
            }

            .tree-title {
                font-weight: bold;
                color: #13c2c2;
                margin-bottom: 10px;
                font-size: 16px;
            }
        }

        .user-list {
            flex: 1;
            max-height: 240px;
            overflow-y: auto;

            &::-webkit-scrollbar {
                width: 6px;
                background: transparent;
            }

            &::-webkit-scrollbar-thumb {
                background: #e6f7ff;
                border-radius: 3px;
            }

            .user-list-title {
                font-weight: bold;
                color: #52c41a;
                margin-bottom: 10px;
                font-size: 16px;
            }

            .user-list-item {
                padding: 6px 0;
                border-radius: 4px;
                transition: background 0.2s;

                &:hover {
                    background: #e6fffb;
                }

                .user-hover {
                    color: #1890ff;
                }
            }

            .empty-tip {
                color: #aaa;
                text-align: center;
                padding: 24px 0;
            }
        }
    }

    .selected-users.card {
        min-height: 56px;

        .selected-title {
            font-weight: bold;
            color: #1890ff;
            margin-bottom: 8px;
            font-size: 15px;
        }

        .selected-tags {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            min-height: 32px;
            align-items: center;

            .empty-tip {
                color: #aaa;
                font-size: 13px;
            }
        }
    }
}
</style>